package com.team.base.common.utils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class DesensitizeUtil {

    // 手机号脱敏正则表达式
    private static final String PHONE_REGEX = "^1[3-9]\\d{9}$";

    // 邮箱脱敏正则表达式
    private static final String EMAIL_REGEX = "^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\\.[a-zA-Z0-9_-]+)+$";

    // 身份证号脱敏正则表达式
    private static final String ID_CARD_REGEX = "^\\d{17}[\\dXx]$";

    /**
     * 脱敏手机号
     * @param phone 手机号
     * @return 脱敏后的手机号
     */
    public static String desensitizePhone(String phone) {
        if (phone == null) {
            return null;
        }
        Pattern pattern = Pattern.compile(PHONE_REGEX);
        Matcher matcher = pattern.matcher(phone);
        if (matcher.matches()) {
            return phone.replaceAll("(\\d{3})\\d{4}(\\d{4})", "$1****$2");
        } else {
            return phone;
        }
    }

    /**
     * 脱敏邮箱
     * @param email 邮箱地址
     * @return 脱敏后的邮箱地址
     */
    public static String desensitizeEmail(String email) {
        if (email == null) {
            return null;
        }
        Pattern pattern = Pattern.compile(EMAIL_REGEX);
        Matcher matcher = pattern.matcher(email);
        if (matcher.matches()) {
            String[] parts = email.split("@");
            String prefix = parts[0];
            if (prefix.length() > 4) {
                int len = prefix.length() - 4;
                prefix = prefix.substring(0, 4) + new String(new char[len]).replace("\0", "*");
            }
            return prefix + "@" + parts[1];
        } else {
            return email;
        }
    }

    /**
     * 脱敏身份证号
     * @param idCard 身份证号
     * @return 脱敏后的身份证号
     */
    public static String desensitizeIdCard(String idCard) {
        if (idCard == null) {
            return null;
        }
        Pattern pattern = Pattern.compile(ID_CARD_REGEX);
        Matcher matcher = pattern.matcher(idCard);
        if (matcher.matches()) {
            return idCard.replaceAll("(\\d{4})\\d{10}(\\w{3})", "$1**********$2");
        } else {
            return idCard;
        }
    }
}
